import produce from 'immer';
import { createAction } from '../utils';
import dataConfig from '../config/dataConfig';

import * as yearbookService from '../services/yearbook';
import * as realtimeService from '../services/realtime';
import light from '../assets/image/light.png';
import dark from '../assets/image/dark.png';
import image from '../assets/image/image.png';


export default {
  namespace: 'global',
  state: {
    //全局
    logged: false,
    currentUser: { id: 0 },
    dataConfig, //数据配置文件，用于初始化专题数据控件，点击时，dataConfig中的项selected属性会变化
    //--------数据选中----------
    selectedDataTime: '', //选中的数据展示层级，同时用于渲染地图图层和表格数据
    selectedDataTimeSeries: [],
    selectedDataId: '', //
    selectedDataTitle: '', //
    selectedDataType: '', // 1.yearbook 2.service
    selectedDataConfig: {},
    selectedData: [], //选中的数据
    selectedAllData:[],//选中类型所有数据
    selectedDataFetching: false,
    selectedDataFetchingByTime: false, //时间变化数据获取状态 区别于 类别 和 level
    //---------20190308-------------
    selectedDataLevel: '630100', //选中的数据展示层级，用于初始化专题数据控件,同时用于渲染地图图层和表格数据
    selectedYearbookDataList: [],
    currentRenderYearbookData: {},
    selectedServiceDataList: [],
    //------------------------
    mapCenter: undefined,
    mapZoomLevel: '630',
    pointAtRegion: { code: '', name: '' },
    selectedDataTypeList: [],
    //------------------------
    baseMapLayers: [
      {
        id: 1,
        image: image,
        title: '影像',
        url: 'https://changsanjiao.shsmi.com/changsanjiao/rest/services/GLOBAL_IMAGE/MapServer',
      },
      {
        id: 2,
        image: light,
        title: '亮色',
        url: 'https://changsanjiao.shsmi.com/changsanjiao/rest/services/20190301/MapServer',
      },
      {
        id: 3,
        image: dark,
        title: '深色',
        url: 'https://changsanjiao.shsmi.com/changsanjiao/rest/services/20190301_dark/MapServer',
      },
    ], //用于初始化BaseMap控件
  },
  reducers: {
    //=================================
    updateState(state, { payload }) {
      return { ...state, ...payload };
    },
    //=================================
    saveMapCenter(state, { payload }) {
      produce(state, draft => {
        draft.mapCenter = payload;
      });
    },
    saveMapZoomLevel(state, { payload }) {
      produce(state, draft => {
        draft.mapZoomLevel = payload;
      });
    },
    savePointAtRegion(state, { payload }) {
      produce(state, draft => {
        draft.pointAtRegion = payload;
      });
    },
    savePopulationData(state, { payload }) {
      produce(state, draft => {
        draft.populationData = payload;
      });
    },
    saveSelectedDataTypeList(state, { payload }) {
      produce(state, draft => {
        draft.selectedDataTypeList = payload;
      });
    },
    saveLogged(state, { payload }) {
      produce(state, draft => {
        draft.logged = payload;
      });
    },
    // saveSelectedTopic(state, { payload }) {
    //   produce(state, draft => {
    //     draft.selectedTopic = payload;
    //   });
    // },
    // saveSelectedTopicItem(state, { payload }) {
    //   produce(state, draft => {
    //     draft.selectedTopicItem = payload;
    //   });
    // },
  },
  effects: {
    //当选中数据的级别、类型、时间发生变化时，触发重新获取数据的操作
    *setSelectedDataLevel(
      {
        payload: { dataLevel },
      },
      { select, put, call }
    ) {
      const { selectedDataLevel } = select(state => state.global);
      if (dataLevel !== selectedDataLevel) {
        yield put({
          type: 'updateState',
          payload: { selectedDataLevel: dataLevel, selectedDataFetching: true },
        });
        yield put({ type: 'updateSelectedData' });
      }
    },
    // *setSelectedDataType({ payload: { dataType } }, { select, put, call }) {
    //   const { selectedDataType } = select(state => state.global);
    //   if (dataType !== selectedDataType) {
    //     yield put({ type: 'updateState', payload: { selectedDataType: dataType } });
    //     yield put({ type: 'updateSelectedData' });
    //   }
    // },
    *setSelectedDataTime(
      {
        payload: { dataTime },
      },
      { select, put, call }
    ) {
      const { selectedDataTime } = select(state => state.global);
      if (dataTime !== selectedDataTime) {
        yield put({
          type: 'updateState',
          payload: { selectedDataTime: dataTime, selectedDataFetchingByTime: true },
        });
        yield put({ type: 'updateSelectedData' });
      }
    },
    *setMapZoomLevel(
      {
        payload: { zoomLevel },
      },
      { select, put, call }
    ) {
      const { selectedDataTypeList } = yield select(state => state.global);
      yield put({ type: 'statData/setDataLevel', payload: { level: zoomLevel } });
      yield put({ type: 'saveMapZoomLevel', payload: zoomLevel });
    },
    *changeSelectedDataType(
      {
        payload: { isAdd, dataType },
      },
      { select, put, call }
    ) {
      const { selectedDataTypeList } = yield select(state => state.global);
      if (isAdd) {
        const nextData = produce(selectedDataTypeList, draft => {
          if (draft.indexOf(dataType) === -1) {
            draft.push(dataType);
          }
        });
        yield put({ type: 'saveSelectedDataTypeList', payload: nextData });
      } else {
        const nextData = produce(selectedDataTypeList, draft => {
          if (draft.indexOf(dataType) !== -1) {
            draft.splice(draft.indexOf(dataType), 1);
          }
        });
        yield put({ type: 'saveSelectedDataTypeList', payload: nextData });
      }
    },
    *changeSelectedData(
      {
        payload: { id, checked, parentConfig, config },
      },
      { select, put }
    ) {
      //修改DataConfig，控制前端控件的勾选状态
      const { dataConfig, selectedYearbookDataList, selectedServiceDataList } = yield select(
        state => state.global
      );
      let selectedDataId = '',
        selectedDataTitle = '',
        selectedDataType = '',
        selectedDataTime = '',
        selectedDataTimeSeries = [],
        selectedDataConfig = {};
      const newDataConfig = produce(dataConfig, draft => {
        draft.map(item => {
          item.children.map(subitem => {
            subitem.children.forEach(l => {
              if (l.id === id) {
                l.selected = checked;
                //保留原状态
                if (checked) {
                  selectedDataId = l.id;
                  selectedDataTitle = l.title;
                  selectedDataType = l.type;
                  if (l.hasTimeLine) {
                    selectedDataTime = l.initTime;
                    selectedDataTimeSeries = [...l.timeSeries];
                  }
                }
              } else {
                // 统计年鉴只能单选  bug:点击 serviceLayer时 会将 geoJsonLayer 关闭
                if (l.type === 'yearbook' && config.type !== 'service') {
                  l.selected = false;
                }
              }
            });
          });
        });
      });
      // yield put(createAction('updateState')({ dataConfig: newDataConfig }))
      yield put(
        createAction('updateState')({
          dataConfig: newDataConfig,
          selectedDataId,
          selectedDataTitle,
          selectedDataType,
          selectedDataTime,
          selectedDataTimeSeries,
          selectedDataFetching: true,
        })
      );
      yield put({ type: 'updateSelectedData' });
      //判断是否为年鉴数据
      if (config.type === 'yearbook') {
        let currentRenderYearbookData = {};
        const newDataList = produce(selectedYearbookDataList, draft => {
          if (checked) {
            draft.push({ id, checked, parentConfig, config });
          } else {
            let index = draft.findIndex(value => value.id === id);
            draft.splice(index, 1);
          }
        });
        if (checked) {
          currentRenderYearbookData = Object.assign({}, { id, checked, parentConfig, config });
        } else {
          if (newDataList.length > 0) {
            currentRenderYearbookData = Object.assign({}, newDataList[newDataList.length - 1]);
          }
        }
        yield put(createAction('updateState')({ selectedYearbookDataList: newDataList }));
        yield put(createAction('updateState')({ currentRenderYearbookData }));
      } else if (config.type === 'service') {
        const newDataList = produce(selectedServiceDataList, draft => {
          if (checked) {
            draft.push({ id, checked, parentConfig, config });
          } else {
            let index = draft.findIndex(value => value.id === id);
            draft.splice(index, 1);
          }
        });
        yield put(createAction('updateState')({ selectedServiceDataList: newDataList }));
      }
    },
    *updateSelectedData(_, { select, put, call }) {
      const {
        selectedDataId,
        selectedDataType,
        selectedDataLevel,
        selectedDataTime,
      } = yield select(state => state.global);
      //根据当前数据选择情况获取数据
      //1.年鉴数据返回具体的数据值
      //2.服务数据直接返回对应的服务
      switch (selectedDataType) {
        case 'yearbook':
          var { status, data } = yield call(yearbookService.fetch, {
            dataId: selectedDataId,
            dataLevel: selectedDataLevel,
            dataTime: selectedDataTime,
          });
          if (status) {
            console.log('select data =>', data);
            yield put(createAction('updateState')({ selectedData: data.content }));

          }
          // 获取全部数据
          var { status, data } = yield call(yearbookService.fetch, {
            dataId: selectedDataId,
            dataLevel: null,
            dataTime: null,
          });
          if (status) {
            console.log('select all data =>', JSON.stringify(data));
            yield put(createAction('updateState')({ selectedAllData: data.content }));
            // 查出全部数据后再 开始渲染
            yield put({
              type: 'updateState',
              payload: { selectedDataFetching: false, selectedDataFetchingByTime: false },
            });
          }
          break;
        case 'service':
          console.log('select data =>', null);
          yield put(createAction('updateState')({ selectedData: null }));
          yield put({
            type: 'updateState',
            payload: { selectedDataFetching: false, selectedDataFetchingByTime: false },
          });
          break;
        // case 'realtime':
        //   const { realtimeStatus, realtimeData } = yield call(realtimeService.fetch, {
        //   });
        //   if (realtimeStatus) {
        //     console.log('select data =>', data);
        //     yield put(createAction('updateState')({ selectedData: realtimeData.content }));
        //     yield put({
        //       type: 'updateState',
        //       payload: { selectedDataFetching: false, selectedDataFetchingByTime: false },
        //     });
        //   }
        //   break;
        case '':
          console.log('select data =>', null);
          yield put(createAction('updateState')({ selectedData: null }));
          yield put({
            type: 'updateState',
            payload: { selectedDataFetching: false, selectedDataFetchingByTime: false },
          });
          break;
      }
    },
    *setLoggedState(
      {
        payload: { loggedState },
      },
      { select, put, call }
    ) {
      yield put({ type: 'saveLogged', payload: loggedState });
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (!pathname.startsWith('/login')) {
          dispatch({
            type: 'userHook',
          });
        }
      });
    },
  },
};
